﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using CustomersSuppliersBusinessLayer;
using CustomersSuppliersDataLayer;
using System.Collections;
using System.IO;
using WebHelper;
using System.Net;
using WebHelper.Handlers;
using WebHelper.Helpers;

namespace CustomersSuppliersWebApplication
{
    public partial class WebFormWorkersAttachments : WebFormBase
    {
        public Guid? Worker_ID
        {
            get
            {
                return string.IsNullOrEmpty(this.Request[BLWorker.PropertiesNames.Worker_ID]) ? (Guid?)null : new Guid(this.Request[BLWorker.PropertiesNames.Worker_ID]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InitializeTelerikRequest(this.RadTextBoxSearch, "onkeyup");
                BLWorker Worker = new BLWorker();
                Worker.Worker_ID = this.Worker_ID;
                Worker.LoadByIdentifiers();
                this.PageTitle ="مرفقات /"+ Worker.Worker_NameAr;
            }
        }
        protected void RadTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            this.getWorkersAttachments();
            this.RadGridResults.Rebind();
        }
        protected void RadComboBoxAttachmentsClassifications_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            this.getWorkersAttachments();
            this.RadGridResults.Rebind();
        }
        protected void RadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            this.getWorkersAttachments();
        }
        
        protected void RadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {
            //exclude attachmentButton from ajaxified
            if (e.Item is GridDataItem)
            {
                RadButton RadButtonAttachments = (RadButton)e.Item.FindControl("RadButtonAttachment");
                if (RadButtonAttachments != null)
                {
                    this.DoPostPackInsteadAjax(RadButtonAttachments);
                }
            }

            //pager
            if (e.Item is GridPagerItem)
            {
                GridPagerItem item = e.Item as GridPagerItem;
                Button changePageSize = (Button)e.Item.FindControl("ChangePageSizeLinkButton");
                changePageSize.Text = "تغيير";
                Button goTO = (Button)e.Item.FindControl("GoToPageLinkButton");
                goTO.Text = "تغيير";
                Label itesNumberLabel = (Label)e.Item.FindControl("ChangePageSizeLabel");
                itesNumberLabel.Text = "          عدد الصفوف :";
                Label goTOLabel = (Label)e.Item.FindControl("GoToPageLabel");
                goTOLabel.Text = "صفحة :";
                Label ofLabel = (Label)e.Item.FindControl("PageOfLabel");
                ofLabel.Text = "من " + item.Paging.PageCount.ToString();
            }
        }
        protected void RadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            //download
            if (e.CommandName == "ShowAttachment")
            {
                BLWorkersAttachment WorkersAttachment = new BLWorkersAttachment();
                WorkersAttachment.WorkerAttachment_ID = new Guid(e.CommandArgument.ToString());
                WorkersAttachment.LoadByIdentifiers();
                DownloadHandler.Download(new Uri(UrlHelper.GetCompleteUri("~/" + WorkersAttachment.File_Path)), WorkersAttachment.File_DisplayName + Path.GetExtension(WorkersAttachment.File_Path),true);
            }

        }
        protected void RadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            BLWorkersAttachment WorkersAttachment = new BLWorkersAttachment();
            WorkersAttachment.Worker_ID = this.Worker_ID;
            
            RadAsyncUpload radAsyncUpload = (RadAsyncUpload)editedItem.FindControl("RadAsyncUploadAttachment");
            if (radAsyncUpload.UploadedFiles.Count == 0)
            {
                this.ShowNotification("من فضلك قم بتحميل الملف", NotificationIconType.Warning);
                e.Canceled = true;
                return;
            }
            UploadedFile file = radAsyncUpload.UploadedFiles[0];
            string ParentDirectory = this.Server.MapPath("~");
            Directory.CreateDirectory(ParentDirectory + "\\WorkersAttachments\\" + this.Worker_ID);
            file.SaveAs(ParentDirectory + "\\WorkersAttachments\\" + this.Worker_ID + "\\" + WorkersAttachment.WorkerAttachment_ID  + file.GetExtension(),true);
            WorkersAttachment.File_Path ="\\WorkersAttachments\\"+ this.Worker_ID + "\\" + WorkersAttachment.WorkerAttachment_ID + file.GetExtension();

            WorkersAttachment.File_DisplayName = file.GetName();
            
            if (newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName] != null && newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName].ToString().Trim()!="")
            {
                WorkersAttachment.File_DisplayName = newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName].ToString();
            }
            if (newValues[BLWorkersAttachment.PropertiesNames.File_Notes] != null)
            {
                WorkersAttachment.File_Notes = newValues[BLWorkersAttachment.PropertiesNames.File_Notes].ToString();
            }

            WorkersAttachment.File_Search = WorkersAttachment.File_DisplayName + WorkersAttachment.File_Notes;

            WorkersAttachment.AutoSave();
            if (WorkersAttachment.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            BLWorkersAttachment WorkersAttachment = new BLWorkersAttachment();
            WorkersAttachment.WorkerAttachment_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLWorkersAttachment.PropertiesNames.WorkerAttachment_ID].ToString());
            WorkersAttachment.LoadByIdentifiers();

            WorkersAttachment.Worker_ID = this.Worker_ID;

            RadAsyncUpload radAsyncUpload = (RadAsyncUpload)editedItem.FindControl("RadAsyncUploadAttachment");
            if (radAsyncUpload.UploadedFiles.Count != 0)
            {
                UploadedFile file = radAsyncUpload.UploadedFiles[0];
                string ParentDirectory = this.Server.MapPath("~");
                Directory.CreateDirectory(ParentDirectory + "\\WorkersAttachments\\" + this.Worker_ID);
                file.SaveAs(ParentDirectory + "\\WorkersAttachments\\" + this.Worker_ID + "\\" + WorkersAttachment.WorkerAttachment_ID + file.GetExtension(), true);
                WorkersAttachment.File_Path = "\\WorkersAttachments\\" + this.Worker_ID + "\\" + WorkersAttachment.WorkerAttachment_ID + file.GetExtension();
                WorkersAttachment.File_DisplayName = file.GetName();
            }
            if (newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName] != null && newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName].ToString().Trim() != "")
            {
                WorkersAttachment.File_DisplayName = newValues[BLWorkersAttachment.PropertiesNames.File_DisplayName].ToString();
            }
            if (newValues[BLWorkersAttachment.PropertiesNames.File_Notes] != null)
            {
                WorkersAttachment.File_Notes = newValues[BLWorkersAttachment.PropertiesNames.File_Notes].ToString();
            }

            WorkersAttachment.File_Search = WorkersAttachment.File_DisplayName + WorkersAttachment.File_Notes;

            WorkersAttachment.AutoSave();
            if (WorkersAttachment.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            BLWorkersAttachment WorkersAttachment = new BLWorkersAttachment();
            WorkersAttachment.WorkerAttachment_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLWorkersAttachment.PropertiesNames.WorkerAttachment_ID].ToString());
            WorkersAttachment.DeleteByIdentifiers();
            if (WorkersAttachment.Error == null)
            {
                this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحذف", NotificationIconType.Error);
                return;
            }
        }
        protected void RadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                //RadBinaryImage display
                RadButton RadButtonAttachments = (RadButton)e.Item.FindControl("RadButtonAttachment");
                if (e.Item.ItemIndex != -1)
                {
                    BLWorkersAttachment WorkersAttachment = (BLWorkersAttachment)e.Item.DataItem;
                    if (WorkersAttachment.File_Path.ToLower().EndsWith(".jpg") || WorkersAttachment.File_Path.ToLower().EndsWith(".jpeg")
                        || WorkersAttachment.File_Path.ToLower().EndsWith(".png") || WorkersAttachment.File_Path.ToLower().EndsWith(".gif"))
                        RadButtonAttachments.Image.ImageUrl = ImageEdittingHandler.GetUrl(UrlHelper.GetCompleteUri( WorkersAttachment.File_Path.Replace("\\", "/")), null, null, 80, 40, null, FlipType.None);
                }
            }

            
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                //width
                GridEditableItem editedItem = e.Item as GridEditableItem;
                GridEditManager editMan = editedItem.EditManager;
                GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)(editMan.GetColumnEditor(BLWorkersAttachment.PropertiesNames.File_Notes));
                editor.TextBoxMode = TextBoxMode.MultiLine;
                editor.TextBoxControl.Width = Unit.Pixel(300);
                editor.TextBoxControl.Height = Unit.Pixel(40);
            }

        }


        private void getWorkersAttachments()
        {
            BLWorkersAttachmentCollection WorkersAttachmentCollection = new BLWorkersAttachmentCollection();
            //Worker id
            WorkersAttachmentCollection.Template.AddFilter(LogicalOperators.And, BLWorkersAttachment.PropertiesNames.Worker_ID, FilterOperators.Equal, this.Worker_ID, typeof(Guid));
           
            //search
            WorkersAttachmentCollection.Template.AddFilter(LogicalOperators.And, BLWorkersAttachment.PropertiesNames.File_Search, FilterOperators.Contains, StringHelper.ToUniqueStatement(this.RadTextBoxSearch.Text), typeof(string));
            
            //load
            WorkersAttachmentCollection.Load();

            this.RadGridResults.DataSource = WorkersAttachmentCollection;
            this.RadGridResults.MasterTableView.DataKeyNames = BLWorkersAttachment.PropertiesNames.Identifiers;
        }

    }
}